<template>
  <div class="case-auto-demo">
    <div class="page-header">
      <h1 class="page-title">案件自动入库演示</h1>
      <div class="header-actions">
        <el-button type="success" @click="simulateCompletion">
          <i class="fas fa-play mr-2"></i>模拟案件办结
        </el-button>
        <el-button type="primary" @click="resetDemo">
          <i class="fas fa-redo mr-2"></i>重置演示
        </el-button>
      </div>
    </div>

    <!-- 流程说明 -->
    <div class="process-description">
      <el-alert
        title="案件自动入库流程说明"
        type="info"
        :closable="false"
        show-icon
      >
        <template #default>
          <p>本演示展示了案件办结后的完整自动化流程：</p>
          <ol>
            <li><strong>案件办结</strong> - 律师完成案件处理，系统检测到案件状态变更</li>
            <li><strong>自动入库</strong> - 系统自动将案件信息添加到案例库，状态设为"待审查"</li>
            <li><strong>AI脱敏</strong> - 系统自动识别并处理敏感信息（身份证、手机号等）</li>
            <li><strong>人工审查</strong> - 管理人员审查脱敏结果和案例质量</li>
            <li><strong>正式入库</strong> - 审查通过后，案例正式发布到案例库</li>
          </ol>
        </template>
      </el-alert>
    </div>

    <!-- 演示案件信息 -->
    <div class="demo-case-info">
      <div class="section-header">
        <h2 class="section-title">演示案件信息</h2>
      </div>
      
      <el-form :model="demoCase" label-width="120px" class="demo-form">
        <div class="form-grid">
          <el-form-item label="案件标题">
            <el-input v-model="demoCase.title" placeholder="请输入案件标题"/>
          </el-form-item>
          <el-form-item label="案件类型">
            <el-select v-model="demoCase.category" placeholder="选择案件类型">
              <el-option label="交通事故" value="traffic"></el-option>
              <el-option label="合同纠纷" value="contract"></el-option>
              <el-option label="劳动纠纷" value="labor"></el-option>
              <el-option label="房产纠纷" value="property"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="承办律师">
            <el-input v-model="demoCase.lawyer" placeholder="请输入律师姓名"/>
          </el-form-item>
          <el-form-item label="案件结果">
            <el-select v-model="demoCase.endType" placeholder="选择案件结果">
              <el-option label="判决" value="judgment"></el-option>
              <el-option label="调解" value="mediation"></el-option>
              <el-option label="和解" value="settlement"></el-option>
              <el-option label="撤诉" value="withdrawal"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="案件金额">
            <el-input-number 
              v-model="demoCase.amount" 
              :min="0" 
              :step="10000"
              controls-position="right"
              placeholder="请输入案件金额"
            />
          </el-form-item>
          <el-form-item label="办结时间">
            <el-date-picker
              v-model="demoCase.completedAt"
              type="date"
              placeholder="选择办结时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </div>
        <el-form-item label="案件摘要">
          <el-input 
            v-model="demoCase.summary" 
            type="textarea" 
            rows="3"
            placeholder="请输入案件摘要"
          />
        </el-form-item>
        <el-form-item label="案件内容">
          <el-input 
            v-model="demoCase.content" 
            type="textarea" 
            rows="5"
            placeholder="请输入包含敏感信息的案件内容（如身份证号、手机号等）"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 流程进度 -->
    <div class="process-progress">
      <div class="section-header">
        <h2 class="section-title">流程进度</h2>
      </div>
      
      <div class="progress-steps">
        <div 
          v-for="(step, index) in processSteps" 
          :key="index"
          class="progress-step"
          :class="getStepClass(step.status)"
        >
          <div class="step-icon">
            <i v-if="step.status === 'completed'" class="fas fa-check"></i>
            <i v-else-if="step.status === 'processing'" class="fas fa-spinner fa-spin"></i>
            <i v-else :class="step.icon"></i>
          </div>
          <div class="step-content">
            <h4>{{ step.title }}</h4>
            <p>{{ step.description }}</p>
            <div v-if="step.status === 'processing'" class="step-progress">
              <el-progress :percentage="step.progress" :show-text="false" />
              <span class="progress-text">{{ step.progress }}%</span>
            </div>
            <div v-if="step.message" class="step-message" :class="step.messageType">
              <i :class="getMessageIcon(step.messageType)"></i>
              {{ step.message }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 结果展示 -->
    <div v-if="processResult" class="result-section">
      <div class="section-header">
        <h2 class="section-title">处理结果</h2>
      </div>
      
      <div class="result-content">
        <el-alert
          :title="processResult.success ? '处理成功' : '处理失败'"
          :type="processResult.success ? 'success' : 'error'"
          :description="processResult.message"
          show-icon
          :closable="false"
        />
        
        <div v-if="processResult.success && processResult.data" class="result-details">
          <h3>生成的案例信息：</h3>
          <div class="case-preview">
            <div class="preview-header">
              <h4>{{ processResult.data.title }}</h4>
              <div class="preview-tags">
                <el-tag :type="getCaseTypeColor(processResult.data.category)" size="small">
                  {{ getCaseTypeText(processResult.data.category) }}
                </el-tag>
                <el-tag type="warning" size="small">{{ processResult.data.status }}</el-tag>
                <el-tag v-if="processResult.data.isUrgent" type="danger" size="small">紧急</el-tag>
              </div>
            </div>
            <div class="preview-content">
              <div class="info-grid">
                <div class="info-item">
                  <label>案例ID：</label>
                  <span>#{{ processResult.data.id }}</span>
                </div>
                <div class="info-item">
                  <label>承办律师：</label>
                  <span>{{ processResult.data.author }}</span>
                </div>
                <div class="info-item">
                  <label>案件金额：</label>
                  <span class="amount">￥{{ processResult.data.amount?.toLocaleString() }}</span>
                </div>
                <div class="info-item">
                  <label>办结时间：</label>
                  <span>{{ processResult.data.completedAt }}</span>
                </div>
                <div class="info-item">
                  <label>入库时间：</label>
                  <span>{{ processResult.data.autoAddedAt }}</span>
                </div>
                <div class="info-item">
                  <label>可见范围：</label>
                  <span>{{ processResult.data.visibleTo.join('、') }}</span>
                </div>
              </div>
              <div class="summary-section">
                <label>案件摘要：</label>
                <p>{{ processResult.data.summary }}</p>
              </div>
            </div>
          </div>
          
          <!-- 敏感信息处理结果 -->
          <div v-if="processResult.data.sensitiveItems?.length" class="sensitive-results">
            <h3>敏感信息识别结果：</h3>
            <div class="sensitive-list">
              <div 
                v-for="item in processResult.data.sensitiveItems" 
                :key="item.id"
                class="sensitive-item"
              >
                <div class="item-type">{{ item.type }}</div>
                <div class="item-process">
                  <span class="original">{{ item.original }}</span>
                  <i class="fas fa-arrow-right"></i>
                  <span class="masked">{{ item.masked }}</span>
                </div>
                <el-tag :type="item.status === 'processed' ? 'success' : 'warning'" size="small">
                  {{ item.status === 'processed' ? '已处理' : '待处理' }}
                </el-tag>
              </div>
            </div>
          </div>
          
          <!-- 下一步操作 -->
          <div class="next-actions">
            <h3>下一步操作：</h3>
            <div class="action-buttons">
              <el-button type="primary" @click="goToCaseReview">
                <i class="fas fa-tasks mr-1"></i>前往案件审查
              </el-button>
              <el-button type="success" @click="goToCaseLibrary">
                <i class="fas fa-folder mr-1"></i>查看案例库
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { simulateCaseCompletion } from '@/api/caseAutoProcess'

export default {
  name: 'CaseAutoDemo',
  setup() {
    const demoCase = reactive({
      title: '重大交通事故人身损害赔偿纠纷案',
      category: 'traffic',
      lawyer: '张律师',
      endType: 'judgment',
      amount: 850000,
      completedAt: new Date().toISOString().split('T')[0],
      summary: '高速公路多车连环追尾事故，造成2人死亡3人重伤，经过6个月的诉讼程序，最终法院判决责任方赔偿85万元。',
      content: '案件详情：2024年1月15日，在沪宁高速公路发生多车连环追尾事故。当事人张某（身份证号：320123199001011234）驾驶苏A12345号车辆，因雨天路滑追尾前车，造成连环追尾。伤者李某（手机号：13812345678）被送往市第一人民医院救治，经鉴定为九级伤残。最终通过法院判决，张某承担主要责任，赔偿医疗费、误工费等共计85万元。'
    })
    
    const processSteps = ref([
      {
        title: '案件办结',
        description: '律师完成案件处理',
        icon: 'fas fa-gavel',
        status: 'pending',
        progress: 0,
        message: '',
        messageType: ''
      },
      {
        title: '自动入库',
        description: '系统自动创建案例',
        icon: 'fas fa-database',
        status: 'pending',
        progress: 0,
        message: '',
        messageType: ''
      },
      {
        title: 'AI脱敏处理',
        description: '自动识别敏感信息',
        icon: 'fas fa-shield-alt',
        status: 'pending',
        progress: 0,
        message: '',
        messageType: ''
      },
      {
        title: '进入审查队列',
        description: '等待管理员审查',
        icon: 'fas fa-user-check',
        status: 'pending',
        progress: 0,
        message: '',
        messageType: ''
      },
      {
        title: '流程完成',
        description: '准备人工审查',
        icon: 'fas fa-check-circle',
        status: 'pending',
        progress: 0,
        message: '',
        messageType: ''
      }
    ])
    
    const processResult = ref(null)
    const isProcessing = ref(false)
    
    const getStepClass = (status) => {
      return {
        'step-pending': status === 'pending',
        'step-processing': status === 'processing',
        'step-completed': status === 'completed',
        'step-error': status === 'error'
      }
    }
    
    const getMessageIcon = (type) => {
      const icons = {
        success: 'fas fa-check-circle',
        error: 'fas fa-exclamation-circle',
        info: 'fas fa-info-circle',
        warning: 'fas fa-exclamation-triangle'
      }
      return icons[type] || 'fas fa-info-circle'
    }
    
    const getCaseTypeColor = (type) => {
      const colors = {
        traffic: 'danger',
        contract: 'primary',
        labor: 'warning',
        property: 'success'
      }
      return colors[type] || 'info'
    }
    
    const getCaseTypeText = (type) => {
      const texts = {
        traffic: '交通事故',
        contract: '合同纠纷',
        labor: '劳动纠纷',
        property: '房产纠纷'
      }
      return texts[type] || '其他'
    }
    
    const updateStep = (stepIndex, status, message = '', messageType = '', progress = 0) => {
      processSteps.value[stepIndex].status = status
      processSteps.value[stepIndex].message = message
      processSteps.value[stepIndex].messageType = messageType
      processSteps.value[stepIndex].progress = progress
    }
    
    const simulateCompletion = async () => {
      if (isProcessing.value) return
      
      if (!demoCase.title || !demoCase.lawyer) {
        ElMessage.warning('请填写完整的案件信息')
        return
      }
      
      isProcessing.value = true
      processResult.value = null
      
      try {
        // 步骤1：案件办结
        updateStep(0, 'processing', '检测到案件状态变更...', 'info')
        await new Promise(resolve => setTimeout(resolve, 1000))
        updateStep(0, 'completed', '案件办结完成', 'success')
        
        // 步骤2：自动入库
        updateStep(1, 'processing', '正在创建案例库条目...', 'info')
        await new Promise(resolve => setTimeout(resolve, 1500))
        updateStep(1, 'completed', '案例已自动入库', 'success')
        
        // 步骤3：AI脱敏处理
        updateStep(2, 'processing', '正在识别敏感信息...', 'info')
        
        // 模拟脱敏进度
        for (let i = 0; i <= 100; i += 20) {
          processSteps.value[2].progress = i
          await new Promise(resolve => setTimeout(resolve, 300))
        }
        
        updateStep(2, 'completed', '敏感信息识别完成', 'success')
        
        // 步骤4：进入审查队列
        updateStep(3, 'processing', '正在分配审查任务...', 'info')
        await new Promise(resolve => setTimeout(resolve, 800))
        updateStep(3, 'completed', '已进入审查队列', 'success')
        
        // 步骤5：流程完成
        updateStep(4, 'processing', '正在生成最终结果...', 'info')
        
        // 调用API完成整个流程
        const result = await simulateCaseCompletion(demoCase)
        
        if (result.success) {
          updateStep(4, 'completed', '自动入库流程完成', 'success')
          processResult.value = result
          ElMessage.success('案件自动入库流程完成！')
        } else {
          updateStep(4, 'error', result.error, 'error')
          processResult.value = result
          ElMessage.error('流程执行失败：' + result.error)
        }
        
      } catch (error) {
        console.error('演示流程出错:', error)
        updateStep(4, 'error', '流程执行出错', 'error')
        ElMessage.error('演示流程出错：' + error.message)
      } finally {
        isProcessing.value = false
      }
    }
    
    const resetDemo = () => {
      // 重置流程状态
      processSteps.value.forEach(step => {
        step.status = 'pending'
        step.message = ''
        step.messageType = ''
        step.progress = 0
      })
      
      processResult.value = null
      isProcessing.value = false
      
      ElMessage.info('演示已重置')
    }
    
    const goToCaseReview = () => {
      this.$router.push('/admin/case-review-process')
    }
    
    const goToCaseLibrary = () => {
      this.$router.push('/admin/cases/library')
    }
    
    return {
      demoCase,
      processSteps,
      processResult,
      isProcessing,
      getStepClass,
      getMessageIcon,
      getCaseTypeColor,
      getCaseTypeText,
      simulateCompletion,
      resetDemo,
      goToCaseReview,
      goToCaseLibrary
    }
  }
}
</script>

<style scoped>
.case-auto-demo {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  color: #1f2937;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.process-description,
.demo-case-info,
.process-progress,
.result-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-header {
  margin-bottom: 20px;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #1f2937;
  margin: 0;
}

.process-description ol {
  margin: 12px 0 0 20px;
  padding: 0;
}

.process-description li {
  margin-bottom: 8px;
  line-height: 1.5;
}

.demo-form {
  margin-top: 16px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.progress-steps {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.progress-step {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 20px;
  border-radius: 8px;
  border: 2px solid #e5e7eb;
  transition: all 0.3s ease;
}

.step-pending {
  background: #f9fafb;
  border-color: #e5e7eb;
}

.step-processing {
  background: #eff6ff;
  border-color: #3b82f6;
  box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
}

.step-completed {
  background: #f0fdf4;
  border-color: #10b981;
}

.step-error {
  background: #fef2f2;
  border-color: #ef4444;
}

.step-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  background: #f3f4f6;
  color: #9ca3af;
  flex-shrink: 0;
}

.step-processing .step-icon {
  background: #dbeafe;
  color: #1e40af;
}

.step-completed .step-icon {
  background: #d1fae5;
  color: #065f46;
}

.step-error .step-icon {
  background: #fecaca;
  color: #dc2626;
}

.step-content {
  flex: 1;
}

.step-content h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.step-content p {
  margin: 0 0 8px 0;
  color: #6b7280;
  font-size: 14px;
}

.step-progress {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.progress-text {
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
}

.step-message {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  padding: 6px 10px;
  border-radius: 4px;
  margin-top: 8px;
}

.step-message.success {
  background: #d1fae5;
  color: #065f46;
}

.step-message.error {
  background: #fecaca;
  color: #dc2626;
}

.step-message.info {
  background: #dbeafe;
  color: #1e40af;
}

.step-message.warning {
  background: #fef3c7;
  color: #92400e;
}

.result-content {
  margin-top: 16px;
}

.result-details {
  margin-top: 20px;
}

.result-details h3 {
  margin: 20px 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.case-preview {
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e7eb;
}

.preview-header h4 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.preview-tags {
  display: flex;
  gap: 8px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item label {
  font-size: 14px;
  color: #6b7280;
  font-weight: 500;
  min-width: 80px;
}

.info-item span {
  font-size: 14px;
  color: #1f2937;
}

.amount {
  color: #10b981 !important;
  font-weight: 600;
}

.summary-section label {
  display: block;
  font-size: 14px;
  color: #6b7280;
  font-weight: 500;
  margin-bottom: 8px;
}

.summary-section p {
  margin: 0;
  color: #1f2937;
  line-height: 1.6;
  background: white;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
}

.sensitive-results {
  margin-top: 20px;
}

.sensitive-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.sensitive-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
}

.item-type {
  background: #e5e7eb;
  color: #374151;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  min-width: 80px;
  text-align: center;
}

.item-process {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  font-family: monospace;
}

.original {
  color: #ef4444;
  background: #fef2f2;
  padding: 2px 6px;
  border-radius: 3px;
}

.masked {
  color: #10b981;
  background: #f0fdf4;
  padding: 2px 6px;
  border-radius: 3px;
}

.next-actions {
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 12px;
}

@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .preview-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .sensitive-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .item-process {
    width: 100%;
  }
}
</style>

